# coding=utf-8
import tornado.web

import WrapCursor
from CommonLib import *
from database.models.ControllerPoint import ControllerPoint
from database.models.DatabaseCommon import *


class GetNewControlPointsHandler(tornado.web.RequestHandler):

    def post(self):
        r = WrapCursor.WrapCursor()

        try:
            ojson = json.loads(self.request.body)
            iid = ojson['controller_id']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error('request data error:' + str(e.message)))
            return
        sql = None
        ret = ""
        data_set = None
        col_name = None

        session = Session()
        if iid == -1:
            sql = """
                select * from ControlPoints where name=""
            """

            filter = {'name': ''}
        else:
            sql = """
                select * from ControlPoints where name="" and controllerid =?
            """
            filter = {'name': '', 'ControllerID': iid}
        points = session.query(ControllerPoint).filter_by(**filter).all()
        jsonret = dict()
        jsonret['Code'] = 0
        data = list()
        jsonret['data'] = data
        for p in points:
            o = dict()
            o['ControllerID'] = p.ControllerID
            o['id'] = p.id
            o['Value'] = p.Value
            o['name'] = p.name
            o['index'] = p.PointIndex
            data.append(o)
        self.write(json.dumps(jsonret))
